package org.nerve.webmagic.utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Base64;

/**
 * org.nerve.webmagic.spider
 * Created by zengxm on 2016/4/20 0020.
 */
public class ImageUtil {

	public String imgToBase64String(final RenderedImage img, final String formatName) {
		final ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			ImageIO.write(img, formatName, Base64.getEncoder().wrap(os));
			return os.toString(StandardCharsets.ISO_8859_1.name());
		} catch (final IOException ioe) {
			throw new UncheckedIOException(ioe);
		}
	}

	public BufferedImage base64StringToImg(final String base64String) {
		try {
			return ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(base64String)));
		} catch (final IOException ioe) {
			throw new UncheckedIOException(ioe);
		}
	}

	public boolean base64StringToImgAndSave(final String base64String, final String filePath) throws IOException {
		if(base64String==null)
			return false;
		BufferedImage bufferedImage=base64StringToImg(base64String);

		File targetFile=new File(filePath);
		File parent=targetFile.getParentFile();
		if(!parent.exists())
			parent.mkdirs();
		ImageIO.write(
				bufferedImage,
				"PNG",
				targetFile);

		return true;
	}

	public boolean base64StringToImgAndSave(final String base64String,final Path path) throws IOException {
		return base64StringToImgAndSave(base64String, path.toString());
	}
}
